﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using RedditWallpaperLib;
using System.Timers;
using System.Threading;
using System.Diagnostics;

namespace RedditWallpaperService
{
    class Program : ServiceBase
    {
        static void Main(string[] args)
        {
            ServiceBase.Run(new Program());            
        }

        private System.Timers.Timer timer;
        private AutoResetEvent autoResetEvent;

        public Program()
        {
            ServiceName = "Reddit Wallpaper Service";
        }

        protected override void OnStart(string[] args)
        {
            base.OnStart(args);

            timer = new System.Timers.Timer();

            timer.Interval = 3600000;
            timer.AutoReset = true;
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);

            timer_Elapsed(null, null);

            timer.Start();

            //autoResetEvent = new AutoResetEvent(false);
            //autoResetEvent.WaitOne();
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (!EventLog.SourceExists("Reddit Wallpaper Service"))
                EventLog.CreateEventSource("Reddit Wallpaper Service", "Application");
            
            EventLog.WriteEntry("Reddit Wallpaper Service", "trying...", EventLogEntryType.Warning, 234);
            
            try
            {
                RedditWallpaper redditWallpaper = new RedditWallpaper();
                redditWallpaper.ChangeWallpaper();
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Reddit Wallpaper Service", ex.ToString(), EventLogEntryType.Warning, 234);
            }
        }

        protected override void OnStop()
        {
            base.OnStop();

            //autoResetEvent.Set();
        }
    }
}
